# -*- coding:utf-8 -*-
"""
放置调用grpc接口获取数据的函数
"""

import time
import grpc
from loguru import logger
import reque_pb2, reque_pb2_grpc


ip = 'localhost'
port = '9090'


def ClientRecall(addr, data):
    ip = addr.get('ip', '')
    port = addr.get('port', '')
    if not ip or not port:
        return None


    try:
        channel = grpc.insecure_channel('%s:%s' % (ip, port))
        stub = reque_pb2_grpc.QuestionServiceStub(channel)
        resp = stub.GetQuestions(request, timeout=2.0)
        # PortraitDecodeReq(**data)为req的请求数据对象，需要从**_pb2.py文件中导入相应的massage类----PortraitDecodeReq

        logger.info('success to call DecodeReq server.')
    except Exception as e:
        logger.error(f'failed to call DecodeReq server,cause: {e}.')
        return None

        # 返回对象
    return resp

if __name__ == '__main__':
    # 客户端链接的主机号和端口号,必须是服务器创建的主机号和端口号.
    addr = {'ip': ip, 'port': port}
    # data = "{'quantity': 10, 'keyword':{'grade':'三年级', 'subject':'数学', 'topic':'算术', 'difficulty':'hard'}}"
    # data_encoded = data.encode('utf-8')
    request = reque_pb2.GetQuestionsRequest(
        quantity=1,
        keyword=reque_pb2.Keyword(
            grade="六年级",
            subject="语文",
            topic= '3',
            difficulty="hard"
        )
    )
    res = ClientRecall(addr, request)
    print(res)


